<template>
  <div class="dish-list-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">菜品浏览</h1>
        <p class="page-subtitle">发现各种美味菜品</p>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="searchQuery"
            placeholder="搜索菜品名称..."
            clearable
            @keyup.enter.native="handleSearch"
            @clear="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="sortBy" placeholder="排序方式" @change="handleSearch">
            <el-option label="默认排序" value=""></el-option>
            <el-option label="价格从低到高" value="price_asc"></el-option>
            <el-option label="价格从高到低" value="price_desc"></el-option>
            <el-option label="名称A-Z" value="name_asc"></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="pageSize" placeholder="每页显示" @change="handleSizeChange">
            <el-option label="12条/页" :value="12"></el-option>
            <el-option label="24条/页" :value="24"></el-option>
            <el-option label="36条/页" :value="36"></el-option>
            <el-option label="48条/页" :value="48"></el-option>
          </el-select>
        </el-col>
      </el-row>
    </div>

    <!-- 菜品列表 -->
    <div class="dishes-section">
      <el-row :gutter="20" v-loading="loading">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="dish in dishes" :key="dish.dishid">
          <el-card class="dish-card" shadow="hover">
            <div class="dish-image">
              <img :src="dish.dishcover || require('@/assets/dishes/dish1.jpg')" :alt="dish.dishname">
              <div class="dish-overlay">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="addToCart(dish)"
                  :disabled="!isLoggedIn"
                >
                  <i class="el-icon-plus"></i> 加入购物车
                </el-button>
              </div>
            </div>
            <div class="dish-info">
              <h3 class="dish-name">{{ dish.dishname }}</h3>
              <p class="dish-price">¥{{ dish.dishprice }}</p>
              <p class="dish-description">{{ dish.dishdescription || '美味可口，值得品尝' }}</p>
              <div class="dish-actions">
                <el-button 
                  type="text" 
                  size="small" 
                  @click="viewDishDetail(dish)"
                >
                  查看详情
                </el-button>
                <el-button 
                  type="text" 
                  size="small" 
                  @click="addToCart(dish)"
                  :disabled="!isLoggedIn"
                >
                  <i class="el-icon-shopping-cart-2"></i> 加入购物车
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 空状态 -->
      <div v-if="!loading && dishes.length === 0" class="empty-state">
        <i class="el-icon-dish empty-icon"></i>
        <p class="empty-text">暂无菜品</p>
        <p class="empty-subtext">请尝试其他搜索条件</p>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper" v-if="total > 0">
      <el-pagination
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        :current-page="currentPage"
        :page-sizes="[12, 24, 36, 48]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getAllDishes } from '@/api/dish'
import { addToCart } from '@/api/cart'

export default {
  name: 'DishList',
  data() {
    return {
      loading: false,
      dishes: [],
      currentPage: 1,
      pageSize: 12,
      total: 0,
      searchQuery: '',
      sortBy: ''
    }
  },
  computed: {
    ...mapGetters(['isLoggedIn', 'userInfo'])
  },
  mounted() {
    // 从路由参数获取搜索条件
    const { keyword } = this.$route.query
    if (keyword) {
      this.searchQuery = keyword
    }
    this.loadDishes()
  },
  methods: {
    // 加载菜品列表
    async loadDishes() {
      this.loading = true
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchQuery
        }
        
        // 添加排序参数
        if (this.sortBy) {
          params.sortBy = this.sortBy
        }

        const response = await getAllDishes(params)
        
        if (response.data && response.data.code === 20000) {
          const pageInfo = response.data.data
          this.dishes = pageInfo.list || []
          this.total = pageInfo.total || 0
        }
      } catch (error) {
        console.error('加载菜品失败:', error)
        this.$message.error('加载菜品失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索菜品
    handleSearch() {
      this.currentPage = 1
      this.loadDishes()
    },

    // 分页变化
    handlePageChange(page) {
      this.currentPage = page
      this.loadDishes()
    },

    // 每页数量变化
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.loadDishes()
    },

    // 添加到购物车
    async addToCart(dish) {
      if (!this.isLoggedIn) {
        this.$message.warning('请先登录')
        this.$router.push('/login')
        return
      }

      try {
        console.log('添加到购物车参数:', {
          dishname: dish.dishname,
          dishprice: dish.dishprice,
          userid: this.userInfo.userid
        })
        
        const response = await addToCart(dish.dishname, dish.dishprice, this.userInfo.userid)
        console.log('购物车API响应:', response)
        
        if (response.data && response.data.code === 20000) {
          this.$message.success('已添加到购物车')
        } else {
          const errorMsg = response.data?.msg || '添加失败'
          console.error('购物车API返回错误:', errorMsg)
          this.$message.error(errorMsg)
        }
      } catch (error) {
        console.error('添加到购物车失败:', error)
        console.error('错误详情:', error.response?.data || error.message)
        this.$message.error('添加到购物车失败: ' + (error.response?.data?.msg || error.message))
      }
    },

    // 查看菜品详情
    viewDishDetail(dish) {
      this.$router.push({
        path: '/dish/detail',
        query: { dishId: dish.dishid }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dish-list-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;

  .page-header {
    text-align: center;
    margin-bottom: 40px;
    
    .header-content {
      .page-title {
        font-size: 36px;
        color: #333;
        margin-bottom: 10px;
      }
      
      .page-subtitle {
        font-size: 18px;
        color: #666;
      }
    }
  }

  .search-filter-section {
    margin-bottom: 30px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
  }

  .dishes-section {
    margin-bottom: 40px;

    .dish-card {
      margin-bottom: 20px;
      transition: transform 0.3s;
      
      &:hover {
        transform: translateY(-5px);
        
        .dish-overlay {
          opacity: 1;
        }
      }

      .dish-image {
        position: relative;
        height: 200px;
        overflow: hidden;
        border-radius: 8px;
        margin-bottom: 15px;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .dish-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.5);
          display: flex;
          align-items: center;
          justify-content: center;
          opacity: 0;
          transition: opacity 0.3s;
        }
      }

      .dish-info {
        .dish-name {
          font-size: 18px;
          color: #333;
          margin: 0 0 10px 0;
          font-weight: bold;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .dish-price {
          font-size: 20px;
          color: #e74c3c;
          font-weight: bold;
          margin: 0 0 10px 0;
        }

        .dish-description {
          color: #666;
          font-size: 14px;
          margin: 0 0 15px 0;
          line-height: 1.4;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }

        .dish-actions {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
      }
    }

    .empty-state {
      text-align: center;
      padding: 60px 20px;
      
      .empty-icon {
        font-size: 64px;
        color: #ddd;
        margin-bottom: 20px;
      }
      
      .empty-text {
        font-size: 18px;
        color: #666;
        margin-bottom: 10px;
      }
      
      .empty-subtext {
        font-size: 14px;
        color: #999;
      }
    }
  }

  .pagination-wrapper {
    text-align: center;
    margin-top: 30px;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dish-list-container {
    padding: 10px;
    
    .page-title {
      font-size: 28px !important;
    }
    
    .search-filter-section {
      .el-col {
        margin-bottom: 10px;
      }
    }
    
    .dish-actions {
      flex-direction: column;
      gap: 10px;
      
      .el-button {
        width: 100%;
      }
    }
  }
}
</style> 